Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
The nanoid npm package is a small, secure, URL-friendly, unique string ID generator for JavaScript applications. It is designed to be fast and efficient, producing random or custom ID strings suitable for a variety of applications, including database keys, session identifiers, and more.
Simple ID Generation
Generate a unique, URL-friendly ID. The default ID length is 21 characters, which provides a good balance of speed and uniqueness.
const { nanoid } = require('nanoid');
console.log(nanoid()); // Example output: 'V1StGXR8_Z5jdHi6B-myT'
Custom Length ID Generation
Generate a unique ID with a custom length. This allows for shorter or longer IDs depending on the level of uniqueness required.
const { nanoid } = require('nanoid');
console.log(nanoid(10)); // Example output: 'IRFa-VaY2b'
Non-secure ID Generation
Generate a non-secure ID with a custom alphabet and length. This is useful for cases where unique IDs are needed without the cryptographic strength.
const { customAlphabet } = require('nanoid');
const nanoid = customAlphabet('1234567890abcdef', 10);
console.log(nanoid()); // Example output: '4f90d13a42'
Custom Alphabet ID Generation
Generate a unique ID using a custom alphabet. This is useful when you need to avoid certain characters or use a specific set of characters for IDs.
const { customAlphabet } = require('nanoid');
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const nanoid = customAlphabet(alphabet, 10);
console.log(nanoid()); // Example output: '4f90d13a42'
The uuid package can generate RFC-compliant UUIDs. It offers different versions of UUIDs, such as v1 (timestamp-based), v4 (random), and others. Compared to nanoid, uuid provides more standardized and structured IDs, but they are not as compact as nanoid's IDs.
Shortid is another package for generating short non-sequential url-friendly unique ids. However, it is no longer recommended for use as it has been deprecated in favor of nanoid, which is more secure and maintains a smaller size.
Uniqid is a package that generates unique IDs based on the current time and an optional prefix or suffix. It is less feature-rich compared to nanoid and does not provide the same level of customization or security.
A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
A-Za-z0-9_-
).
So ID size was reduced from 36 to 21 symbols.const nanoid = require('nanoid')
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Supports all browsers, Node.js and React Native.
Nano ID is quite comparable to UUID v4 (random-based). It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability:
For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.
There are three main differences between Nano ID and UUID v4:
uuid/v4
package:
119 bytes instead of 435.$ ./test/benchmark
nanoid 693,132 ops/sec
nanoid/generate 624,291 ops/sec
uid.sync 487,706 ops/sec
uuid/v4 471,299 ops/sec
secure-random-string 448,386 ops/sec
shortid 66,809 ops/sec
Async:
nanoid/async 105,024 ops/sec
nanoid/async/generate 106,682 ops/sec
secure-random-string 94,217 ops/sec
uid 92,026 ops/sec
Non-secure:
nanoid/non-secure 2,555,814 ops/sec
rndm 2,413,565 ops/sec
nanoid-dictionary
with popular alphabets to use with nanoid/generate
.nanoid-cli
to generate ID from CLI.nanoid-good
to be sure that your ID doesn't contain any obscene words.See a good article about random generators theory: Secure random values (in Node.js)
Instead of using the unsafe Math.random()
, Nano ID uses the crypto
module
in Node.js and the Web Crypto API in browsers. These modules use unpredictable
hardware random generator.
random % alphabet
is a popular mistake to make when coding an ID generator.
The spread will not be even; there will be a lower chance for some symbols
to appear compared to others—so it will reduce the number of tries
when brute-forcing.
Nano ID uses a better algorithm and is tested for uniformity.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
The main module uses URL-friendly symbols (A-Za-z0-9_-
) and returns an ID
with 21 characters (to have a collision probability similar to UUID v4).
const nanoid = require('nanoid')
model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
If you want to reduce ID length (and increase collisions probability), you can pass the length as an argument.
nanoid(10) //=> "IRFa-VaY2b"
Don’t forget to check the safety of your ID length in our ID collision probability calculator.
You can also use custom alphabet or random generator.
Do not use a nanoid for key
prop. In React key
should be consistence
between renders. This is bad code:
<Item key={nanoid()} /> /* DON’T DO IT */
This is good code. id
will be generated only once:
const Element = () => {
const [id] = React.useState(nanoid)
return <Item key={id}>
}
If you want to use Nano ID for id
, you must to set some string prefix.
Nano ID could be started from number. HTML ID can’t be started from the number.
<input id={'id' + this.id} type="text"/>
React Native doesn’t have built-in random generator.
expo-random
] docs and install it.nanoid/async
instead of synchronous nanoid
.const nanoid = require('nanoid/async')
async function createUser () {
user.id = await nanoid()
}
In PouchDB and CouchDB, IDs can’t start with an underscore _
.
A prefix is required to prevent this issue, as Nano ID might use a _
at the start of the ID by default.
Override the default ID with the following option:
db.put({
_id: 'id' + nanoid(),
…
})
const mySchema = new Schema({
_id: {
type: String,
default: () => nanoid()
}
})
Web Workers don’t have access to a secure random generator.
Security is important in IDs, when IDs should be unpredictable. For instance, in “access by URL” link generation.
If you don’t need unpredictable IDs, but you need Web Workers support, you can use non‑secure ID generator. Note, that they have bigger collision probability.
const nanoid = require('nanoid/non-secure')
nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Nano ID was ported to many languages. You can use these ports to have the same ID generators on client and server side.
Also, CLI tool is available to generate IDs from a command line.
To generate hardware random bytes, CPU will collect electromagnetic noise. During the collection, CPU doesn’t work.
If we will use asynchronous API for random generator, another code could be executed during the entropy collection.
const nanoid = require('nanoid/async')
async function createUser () {
user.id = await nanoid()
}
Unfortunately, you will not have any benefits in a browser, since Web Crypto API doesn’t have asynchronous API.
By default, Nano ID uses hardware random generator for security and low collision probability. If you don’t need it, you can use very fast non-secure generator.
const nonSecure = require('nanoid/non-secure')
const id = nonSecure() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Note that it is predictable and have bigger collision probability.
If you want to change the ID's alphabet or length
you can use the low-level generate
module.
const generate = require('nanoid/generate')
model.id = generate('1234567890abcdef', 10) //=> "4f90d13a42"
Check the safety of your custom alphabet and ID length
in our ID collision probability calculator.
You can find popular alphabets in nanoid-dictionary
.
Alphabet must contain 256 symbols or less. Otherwise, the generator will not be secure.
Asynchronous and non-secure API is also available:
const generate = require('nanoid/async/generate')
async function createUser () {
user.id = await generate('1234567890abcdef', 10)
}
const generate = require('nanoid/non-secure/generate')
user.id = generate('1234567890abcdef', 10)
You can replace the default safe random generator using the format
module.
For instance, to use a seed-based generator.
const format = require('nanoid/format')
function random (size) {
const result = []
for (let i = 0; i < size; i++) {
result.push(randomByte())
}
return result
}
format(random, "abcdef", 10) //=> "fbaefaadeb"
random
callback must accept the array size and return an array
with random numbers.
If you want to use the same URL-friendly symbols with format
,
you can get the default alphabet from the url
file.
const url = require('nanoid/url')
format(random, url, 10) //=> "93ce_Ltuub"
Asynchronous API is also available:
const format = require('nanoid/async/format')
const url = require('nanoid/url')
function random (size) {
return new Promise(…)
}
async function createUser () {
user.id = await format(random, url, 10)
}
FAQs
A tiny (116 bytes), secure URL-friendly unique string ID generator
The npm package nanoid receives a total of 35,210,619 weekly downloads. As such, nanoid popularity was classified as popular.
We found that nanoid demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.